#pragma once


#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <cerrno>
#include <cstring>
#include <cstdlib>
#include <string>
#include <unistd.h>

const char *pathname ="home/xiaoliu";
const int proj_id=0x66;
const int defaultsize =4096;

std::string ToHex(key_t k)
{
    char buffer[1024];
    snprintf(buffer, sizeof(buffer), "0x%x", k);
    return buffer;
}

key_t GetShmKey()
{
    key_t k=ftok(pathname,proj_id);
    if(k<0)
    {
         std::cerr << "ftok error, errno : " << errno << ", error string: " << strerror(errno) << std::endl;
        return -1;
    }
    return k;
}

int CreateShmOrDie(key_t key, int size, int flag)
{
    int shmid = shmget(key, size, flag);
    if (shmid < 0)
    {
        std::cerr << "shmget error, errno : " << errno << ", error string: " << strerror(errno) << std::endl;
        exit(2);
    }
    return shmid;
}

int CreateShm(key_t key, int size)
{
    // IPC_CREAT: 不存在就创建，存在就获取
    // IPC_EXCL: 没有意义
    // IPC_CREAT | IPC_EXCL: 不存在就创建，存在就出错返回
    return CreateShmOrDie(key, size, IPC_CREAT | IPC_EXCL | 0666);
}

int GetShm(key_t key, int size)
{
    return CreateShmOrDie(key, size, IPC_CREAT);
}

void DeleteShm(int shmid)
{
    int flag=shmctl(shmid,IPC_SET,nullptr);
    if(flag==-1)
    {
        std::cout<<"delete fail!"<<std::endl;
    }
    else
    {
        std::cout<<"delete successd!"<<std::endl;
    }
}

void* ShmAttach(int shmid)
{
    void* addr = shmat(shmid,nullptr,0);
    if((long long int)addr == -1)
    {
        std::cout<<"shmat fail!"<<std::endl;
        return nullptr;
    }
    else
    {
        std::cout<<"shmat successd!"<<std::endl;
    }
    return addr;
}

void ShmDetach(void *addr)
{
    int n = shmdt(addr);
    if (n < 0)
    {
        std::cerr << "shmdt error" << std::endl;
    }
}